/*
Version 2.2

Thanit@, Suparerk@

- fix bug IE7 display
- fix sub of sub display rule
- now make section of menu not with Accordian
- require jquery UI
- not use Accordian
- fix active action
- custom icon
- no limit  child
- add expand All feature

****require TW.API****

sample data
{
    "data": [
		{ "id" : "a1", "caption" : "Menu 1", "link" : null, "icon" : null, "child" : [
			{ "id" : "a11", "caption" : "Menu 1.1", "link" :  null, "icon" : null, "child" : null },
			{ "id" : "a12", "caption" : "Menu 1.2", "link" :  null, "icon" : null, "child" : null },
			{ "id" : "a13", "caption" : "Menu 1.3", "link" :  null, "icon" : null, "child" : null }
		]},
		{ "id" : "a2", "caption" : "Menu 2", "link" : null, "icon" : "header-home", "child" : [
			{ "id" : "a21", "caption" : "Menu 2.1", "link" :  null, "icon" : null, "child" : [
				{ "id" : "a211", "caption" : "Menu 2.1.1", "link" :  null, "icon" : null, "child" : null },
				{ "id" : "a212", "caption" : "Menu 2.1.2", "link" :  null, "icon" : null, "child" : null },
				{ "id" : "a213", "caption" : "Menu 2.1.3", "link" :  null, "icon" : null, "child" : [
					{ "id" : "a2131", "caption" : "Menu 2.1.3.1", "link" :  null, "icon" : null, "child" : [
						{ "id" : "a21311", "caption" : "Menu 2.1.3.1.1", "link" :  null, "icon" : null, "child" : null}
					]}
				] }
			]},
			{ "id" : "a22", "caption" : "Menu 2.2", "link" :  null, "icon" : null, "child" : [
				{ "id" : "a221", "caption" : "Menu 2.2.1", "link" :  null, "icon" : null, "child" : null },
				{ "id" : "a222", "caption" : "Menu 2.2.2", "link" :  null, "icon" : null, "child" : null },
				{ "id" : "a223", "caption" : "Menu 2.2.3", "link" :  null, "icon" : null, "child" : null }
			]}
		]},
		{ "id" : "a3", "caption" : "Menu 3", "link" : null, "icon" : null, "child" : [
			{ "id" : "a31", "caption" : "Menu 3.1", "link" :  null, "icon" : null, "child" : null },
			{ "id" : "a32", "caption" : "Menu 3.2", "link" :  null, "icon" : null, "child" : null },
			{ "id" : "a33", "caption" : "Menu 3.3", "link" :  null, "icon" : null, "child" : null }
		]},
		{ "id" : "a4", "caption" : "Menu 3", "link" : null, "icon" : "header-admin", "child" :null}
    ]
}

CSS (ui.sideMenu.css, * ui.icon.sideMenu.css * if have icon)
*/
(function($) {
    ///Menu Builder

    jQuery.fn.buildSideMenu = function(settings) {
        var defaults = { dataURL: "sidemenudata.txt", loadTo: "#contentsHolder", expandAll: false, activeMenu: null }
        var options = jQuery.extend(defaults, settings);

        var holder = $(this);

        holder.html('<div class="openPage ui-state-processing"><img src="' + CDNname + 'images/loading.gif" alt="loading" align="absmiddle"/>Loading menu...</div>');

        $.getJSON(options.dataURL, function(data) {
            var menuObj = data.data;
            var tabIndex = 0; //tabindex
            holder.html("");
            $(menuObj).each(function(i) {
                if (menuObj[i].child != null && menuObj[i].child != "") {
                    //menu name
                    holder.append('<div class="ui-tw-sideMenuSection ui-state-default ui-corner-all ui-helper-clearfix" tabindex="' + tabIndex + '" id="sideMenu' + menuObj[i].id.toString() + '"><span class="ui-icon ui-icon-triangle-1-e"></span><span class="ui-tw-topmenuName">' + menuObj[i].caption.toString() + '</span></div>');
                    //config menu
                    var tmpMenu = $('div#sideMenu' + menuObj[i].id.toString());
                    /*** add icon ***********/
                    //*have icon ?
                    if (menuObj[i].icon != null && menuObj[i].icon != "") {
                        tmpMenu.find(".ui-icon").before('<span class="sideMenuIcon ' + menuObj[i].icon.toString() + '"></span>').css('margin-top', 15);
                        tmpMenu.find("span").css({ 'line-height': '50px' });
                    }

                    //list submenu
                    tmpMenu.after('<div id="detail' + menuObj[i].id.toString() + '" class="ui-tw-subOfSideMenu ui-corner-bottom ui-state-default ui-helper-clearfix"></div>');
                    $('div#detail' + menuObj[i].id.toString()).append('<ul class="category topCategory" id="subMenu' + menuObj[i].id.toString() + '"></ul>').hide();

                    $(menuObj[i].child).each(function(d) {//child  loop *have dicimal*

                        $('ul#subMenu' + menuObj[i].id.toString()).append('<li id="childsubMenu' + menuObj[i].child[d].id.toString() + '" link="' + menuObj[i].child[d].link + '"><a href="#">' + menuObj[i].child[d].caption.toString() + '</a></li>');

                        if (menuObj[i].child[d].child != null && menuObj[i].child[d].child != "") {//childsubMenu loops
                            buildSideMenu_createChild(holder, menuObj[i].child[d]);
                        };

                    });
                    /***sideMenuSection event ***********/
                    tmpMenu.click(function() {
                        //remove other active
                        holder.find("div.ui-state-focus").removeClass('ui-state-focus');
                        //active this
                        $(this).toggleClass("ui-state-focus");

                        $('div#detail' + menuObj[i].id.toString()).slideToggle('normal', function() {
                            if ($(this).offset().top + $(this).height() > holder.height()) {
                                holder.scrollTop($(this).height() + 50);
                            }
                        });
                        $(".ui-tw-sideMenuNavigate").removeClass("ui-state-active");
                        if ($(this).find(".ui-icon-triangle-1-e").size() > 0) {
                            $(this).find(".ui-icon").removeClass("ui-icon-triangle-1-e").addClass("ui-icon-triangle-1-s");
                        } else {
                            $(this).find(".ui-icon").removeClass("ui-icon-triangle-1-s").addClass("ui-icon-triangle-1-e");
                        };
                    }).hover(function() { $(this).addClass("ui-state-hover") }, function() { $(this).removeClass("ui-state-hover") }).disableSelection();

                }
                else {
                    //navi only
                    holder.append('<div class="ui-tw-sideMenuNavigate ui-state-default ui-corner-all ui-helper-clearfix" tabindex="' + tabIndex + '" id="sideMenu' + menuObj[i].id.toString() + '" link="' + menuObj[i].link + '"><span class="ui-tw-topmenuName">' + menuObj[i].caption.toString() + '</span	></div>');
                    //config menu
                    var tmpMenu = $('div#sideMenu' + menuObj[i].id.toString());
                    /*** add icon ***********/
                    //*have icon ?
                    if (menuObj[i].icon != null && menuObj[i].icon != "") {
                        tmpMenu.prepend('<span class="sideMenuIcon ' + menuObj[i].icon.toString() + '"></span>');
                        tmpMenu.find("span").css({ 'line-height': '50px' });
                    }
                    /***sideMenuNavigate event ***********/
                    tmpMenu.click(function() {
                        //remove other active
                        holder.find("div.ui-state-focus").removeClass('ui-state-focus');
                        //active this
                        $(this).addClass("ui-state-focus");

                        $('div#detail' + menuObj[i].id.toString()).slideToggle('normal', function() {
                            if ($(this).offset().top + $(this).height() > holder.height()) {
                                holder.scrollTop($(this).height() + 50);
                            }
                        });
                    }).hover(function() { $(this).addClass("ui-state-hover") }, function() { $(this).removeClass("ui-state-hover") }).disableSelection();
                }
                tabIndex++;
            });

            //active link
            holder.find(".ui-tw-sideMenuNavigate").click(function() {
                if ($(this).attr('link') != null && $(this).attr('link') != '') {
					//fix ---del validate div
					$(".formErrorContent").parent().remove();
					//
                    switchPage(options.loadTo, $(this).attr('link'))
                }
            });
            /******submenu event********/
            $(".category li").click(function() {
                if ($(this).attr('link') != null && $(this).attr('link') != '') {
					//fix ---del validate div
					$(".formErrorContent").parent().remove();
					//
                    switchPage(options.loadTo, $(this).attr('link')); // require TW.API
                }
                holder.find(".category li").css({ 'font-weight': 'normal' }).removeClass("ui-state-focus");
                $(this).addClass("ui-state-focus ui-corner-all").css({ 'font-weight': 'bold', 'padding': '2px' }).siblings().removeClass("ui-state-focus").css({ 'font-weight': 'normal' });
                /*holder.find(".category li").css({'font-weight':'normal'});
                $(this).css({'font-weight':'bold'}).siblings().css({'font-weight':'normal'});*/
            }).toggle(function() {
                $(this).next("ul").slideDown(500, function() {
                    $(this).prev("li").find("a").removeClass("ui-state-active").css("padding", 2);
                });
            }, function() {
                $(this).next("ul").slideUp(500, function() {
                    $(this).prev("li").find("a").addClass("ui-state-active").css("padding", 2);
                });
            });
            //end submenu event
            if (options.expandAll) {
                $(".ui-tw-sideMenuSection, li[hasChild]").click();
            }
            //
            if (options.activeMenu) {
                //alert($("li#childsubMenu"+options.activeMenu).size())
                var clickItem = options.activeMenu.split(",");
                $(clickItem).each(function(i) {
                    $("div#sideMenu" + clickItem[i]).click(); 		   	//alert("li#childsubMenu"+clickItem[i])
                    $("li#childsubMenu" + clickItem[i]).click();
                })
            }

        });
    };
    //end ///Menu Builder

})(jQuery);
/********* create all Child in obj *****************************************/
function buildSideMenu_createChild(holder,obj){
	//alert(obj.caption);
	 var menuName = holder.find('li#childsubMenu' + obj.id.toString()).attr("hasChild",true).after('<ul class="category" style="display:none" id="subMenu' + obj.id.toString() + '"/>').find("a").eq(0).text();
	 //
	 holder.find('li#childsubMenu' + obj.id.toString()).find("a").addClass("ui-state-hover ui-corner-all ui-helper-clearfix").css({"padding":2,'font-weight':'bold','display':'block','clear':'both'}).html("").append('<span class="ui-icon ui-icon-arrowthickstop-1-s" style="float:right"></span><span>'+menuName+'</span>');
	$(obj.child).each(function(j) {//loop in child
		//create child list   
		holder.find('ul#subMenu' + obj.id.toString()).append('<li id="childsubMenu' + obj.child[j].id.toString()  + '" link="'+ obj.child[j].link + '"><a href="#">' + obj.child[j].caption.toString() + '</a></li>');
		if(obj.child[j].child){// if have child
			buildSideMenu_createChild(holder,obj.child[j]);//do again
		};
	});
};

